<?php

namespace app\worker\controller;
use app\common\lib\Str;
use app\common\model\mysql\OrderProductNormal;
use app\common\model\mysql\OrderProductWater;
use app\common\model\mysql\Product;
use app\common\model\mysql\Send as SendModel;
use app\common\model\mysql\Order as OrderModel;
use app\common\model\mysql\SendProduct;
use app\common\model\mysql\WarehouseSpaceProduct;
use app\common\model\mysql\Worker;
use think\facade\Db;

class Send extends AuthBase
{
    /**
     * 准备出厂（生成配送单）
     * @return \think\response\Json
     */
    public function addSingle(){
        $goodsData = $this->request->param('goodsData','');
        /*$goodsData = [
            [
                'product_id'=>1,
                'product_name'=>'景田',
                'tcount'=>2,
                'warehouse_id'=>1,
                'warehouse_space_id'=>1,
                'warehouse_name'=>'水库',
                'warehouse_space_name'=>'默认',
            ],
            [
                'product_id'=>2,
                'product_name'=>'甘露',
                'tcount'=>1,
                'warehouse_id'=>1,
                'warehouse_space_id'=>1,
                'warehouse_name'=>'水库',
                'warehouse_space_name'=>'默认',
            ]
        ];*/
        try {
            Db::startTrans(); // 开始事务
            $sendWhere = [
                ['worker_id_send','=',$this->workerId],
                ['company_id','=',$this->companyId],
                ['is_still_bucket_ticket','=',2],
                ['isdel','=','0'],
            ];
            $sendData = (new SendModel())->getSendFind($sendWhere);
            if($sendData){
                $send_id = $sendData['send_id'];
                if($sendData['stateenum'] == 1){
                    $orderWhere = [
                        ['worker_id_send','=',$this->workerId],
                        ['company_id','=',$this->companyId],
                        ['stateenum','in',[2,64]],
                        ['ordertypeenum','=',1],
                        ['iscancel','=',0],
                    ];
                    $orderIdArr = (new OrderModel())->getNormalOrderFiledArr($orderWhere,'order_id');
                    if(empty($orderIdArr)){
                        return show(config("status.error"),"缺少参数订单数据");
                    }
                    $orderWaterWhere = [
                        ['order_id','in',$orderIdArr]
                    ];
                    $orderWaterCount = (new OrderProductWater())->getOrderProductWaterSum($orderWaterWhere);
                    $sendSaveData['stateenum'] = 2;
                    $sendSaveData['totalcount'] = $orderWaterCount;
                    $sendSaveData['ordercount'] = count($orderIdArr);
                    $sendSaveData['adddate'] = date("Y-m-d H:i:s",time());
                    (new SendModel())->saveSendData($sendData['send_id'],$sendSaveData);
                }
                elseif($sendData['stateenum'] == 2){
                    $orderWhere = [
                        ['worker_id_send','=',$this->workerId],
                        ['send_id','=',$sendData['send_id']],
                        ['company_id','=',$this->companyId],
                        ['ordertypeenum','=',1],
                        ['iscancel','=',0],
                    ];
                    $orderIdArr = (new OrderModel())->getNormalOrderFiledArr($orderWhere,'order_id');
                    if(empty($orderIdArr)){
                        return show(config("status.error"),"缺少参数订单数据");
                    }
                    $orderWaterWhere = [
                        ['order_id','in',$orderIdArr]
                    ];
                    $orderWaterCount = (new OrderProductWater())->getOrderProductWaterSum($orderWaterWhere);
                    $ordercount = count($orderIdArr);
                    $orderIscancelWhere = [
                        ['worker_id_send','=',$this->workerId],
                        ['send_id','=',$sendData['send_id']],
                        ['company_id','=',$this->companyId],
                        ['ordertypeenum','=',1],
                        ['iscancel','=',1],
                        ['stateenum','=',4],
                    ];
                    $orderWaterCountIscancelArr = (new OrderModel())->getNormalOrderFiledArr($orderIscancelWhere,'order_id');
                    if($orderWaterCountIscancelArr){
                        $orderWaterIscancelWhere = [
                            ['order_id','in',$orderWaterCountIscancelArr]
                        ];
                        $orderWaterCountIscancel = (new OrderProductWater())->getOrderProductWaterSum($orderWaterIscancelWhere);
                        $orderWaterCount = $orderWaterCount+$orderWaterCountIscancel;
                        $ordercount = $ordercount+count($orderWaterCountIscancelArr);
                    }
                    $sendSaveData['stateenum'] = 2;
                    $sendSaveData['totalcount'] = $orderWaterCount;
                    $sendSaveData['ordercount'] = $ordercount;
                    $sendSaveData['adddate'] = date("Y-m-d H:i:s",time());
                    (new SendModel())->saveSendData($sendData['send_id'],$sendSaveData);
                    foreach ($orderIdArr as $orderId) {
                        $orderStateWhere = [
                            ['order_id','=',$orderId]
                        ];
                        $orderStateData = (new OrderModel())->getOrderFind($orderStateWhere,'stateenum');
                        if($orderStateData['stateenum'] == 2){
                            $saveOrderData['send_id'] = $send_id;
                            $saveOrderData['stateenum'] = 64;
                        }elseif($orderStateData['stateenum'] == 64){
                            $saveOrderData['send_id'] = $send_id;
                            $saveOrderData['stateenum'] = 64;
                        }
                        (new OrderModel())->saveOrderData($orderId,$saveOrderData);
                    }
                }elseif($sendData['stateenum'] == 4){
                    $orderWhere = [
                        ['worker_id_send','=',$this->workerId],
                        ['send_id','=',$sendData['send_id']],
                        ['company_id','=',$this->companyId],
                        ['ordertypeenum','=',1],
                        ['stateenum','=',2],
                        ['iscancel','=',0],
                    ];
                    $orderIdArr = (new OrderModel())->getNormalOrderFiledArr($orderWhere,'order_id');
                    if(empty($orderIdArr)){
                        return show(config("status.error"),"已有配送单未完成,请先完成");
                    }
                    $orderWaterWhere = [
                        ['order_id','in',$orderIdArr]
                    ];
                    $orderWaterCount = (new OrderProductWater())->getOrderProductWaterSum($orderWaterWhere);
                    $sendSaveData['stateenum'] = 2;
                    $sendSaveData['totalcount'] = $orderWaterCount+$sendData['totalcount'];
                    $sendSaveData['ordercount'] = count($orderIdArr)+$sendData['ordercount'];
                    $sendSaveData['adddate'] = date("Y-m-d H:i:s",time());
                    (new SendModel())->saveSendData($sendData['send_id'],$sendSaveData);
                    foreach ($orderIdArr as $orderId) {
                        $saveOrderData['stateenum'] = 64;
                        (new OrderModel())->saveOrderData($orderId,$saveOrderData);
                    }
                }elseif($passSendOrder['stateenum'] == 32){
                    $orderWhere = [
                        ['worker_id_send','=',$this->workerId],
                        ['company_id','=',$this->companyId],
                        ['stateenum','=',2],
                        ['ordertypeenum','=',1],
                        ['iscancel','=',0],
                    ];
                    $orderIdArr = (new OrderModel())->getNormalOrderFiledArr($orderWhere,'order_id');
                    if(empty($orderIdArr)){
                        return show(config("status.error"),"缺少参数订单数据");
                    }
                    $orderWaterWhere = [
                        ['order_id','in',$orderIdArr]
                    ];
                    $orderWaterCount = (new OrderProductWater())->getOrderProductWaterSum($orderWaterWhere);
                    $sendAddData['stateenum'] = 2;
                    $sendAddData['totalcount'] = $orderWaterCount;
                    $sendAddData['ordercount'] = count($orderIdArr);
                    $sendAddData['adddate'] = date("Y-m-d H:i:s",time());
                    $sendAddData['company_id'] = $this->companyId;
                    $sendAddData['shop_id'] = $this->shopId;
                    $sendAddData['worker_id_send'] = $this->workerId;
                    $sendAddData['worker_name_send'] = $this->workerName;
                    $sendAddData['send_sn'] = (new Str())->makeOrderNo($this->shopId, 2);
                    $send_id = (new SendModel())->addSendData($sendAddData);
                    if($send_id){
                        foreach ($orderIdArr as $orderId) {
                            $saveOrderData['send_id'] = $send_id;
                            $saveOrderData['stateenum'] = 64;
                            (new OrderModel())->saveOrderData($orderId,$saveOrderData);
                        }
                    }
                }else{
                    $orderWhere = [
                        ['worker_id_send','=',$this->workerId],
                        ['company_id','=',$this->companyId],
                        ['stateenum','=',2],
                        ['ordertypeenum','=',1],
                        ['iscancel','=',0],
                    ];
                    $orderIdArr = (new OrderModel())->getNormalOrderFiledArr($orderWhere,'order_id');
                    if(empty($orderIdArr)){
                        return show(config("status.error"),"缺少参数订单数据");
                    }
                    $orderWaterWhere = [
                        ['order_id','in',$orderIdArr]
                    ];
                    $orderWaterCount = (new OrderProductWater())->getOrderProductWaterSum($orderWaterWhere);
                    $sendAddData['stateenum'] = 2;
                    $sendAddData['totalcount'] = $orderWaterCount;
                    $sendAddData['ordercount'] = count($orderIdArr);
                    $sendAddData['adddate'] = date("Y-m-d H:i:s",time());
                    $sendAddData['company_id'] = $this->companyId;
                    $sendAddData['shop_id'] = $this->shopId;
                    $sendAddData['worker_id_send'] = $this->workerId;
                    $sendAddData['worker_name_send'] = $this->workerName;
                    $sendAddData['send_sn'] = (new Str())->makeOrderNo($this->shopId, 2);
                    $send_id = (new SendModel())->addSendData($sendAddData);
                    foreach ($orderIdArr as $orderId) {
                        $saveOrderData['send_id'] = $send_id;
                        $saveOrderData['stateenum'] = 64;
                        (new OrderModel())->saveOrderData($orderId,$saveOrderData);
                    }
                }
            } else {
                $orderWhere = [
                    ['worker_id_send','=',$this->workerId],
                    ['company_id','=',$this->companyId],
                    ['stateenum','=',2],
                    ['ordertypeenum','=',1],
                    ['iscancel','=',0],
                ];
                $orderIdArr = (new OrderModel())->getNormalOrderFiledArr($orderWhere,'order_id');
                if(empty($orderIdArr)){
                    return show(config("status.error"),"缺少参数订单数据");
                }
                $orderWaterWhere = [
                    ['order_id','in',$orderIdArr]
                ];
                $orderWaterCount = (new OrderProductWater())->getOrderProductWaterSum($orderWaterWhere);
                $sendAddData['stateenum'] = 2;
                $sendAddData['totalcount'] = $orderWaterCount;
                $sendAddData['ordercount'] = count($orderIdArr);
                $sendAddData['adddate'] = date("Y-m-d H:i:s",time());
                $sendAddData['company_id'] = $this->companyId;
                $sendAddData['shop_id'] = $this->shopId;
                $sendAddData['worker_id_send'] = $this->workerId;
                $sendAddData['worker_name_send'] = $this->workerName;
                $sendAddData['send_sn'] = (new Str())->makeOrderNo($this->shopId, 2);
                $send_id = (new SendModel())->addSendData($sendAddData);
                if($send_id){
                    foreach ($orderIdArr as $orderId) {
                        $saveOrderData['send_id'] = $send_id;
                        $saveOrderData['stateenum'] = 64;
                        (new OrderModel())->saveOrderData($orderId,$saveOrderData);
                    }
                }
            }
            if($goodsData){
                $this->singleStorage($send_id,$goodsData);
            }
            // 提交事务
            Db::commit();
            return show(config('status.success'), "操作成功", ['send_id'=>$send_id]);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return show(config('status.error'),$e->getMessage());
        } finally {
            // echo 'This will always be executed.';
        }
    }

    /**
     * 配送单拿货记录
     * @param $send_id
     * @param $goodsData
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function singleStorage($send_id,$goodsData){
        $sendProductWhere = $sendWhere = [
            ['send_id','=',$send_id]
        ];
        $sendProductData = (new SendProduct())->getNormalSendProduct($sendProductWhere);
        if($sendProductData){
            $stateenumSend = (new SendModel())->getSendFind($sendWhere,'stateenum');
            if($stateenumSend['stateenum'] == 2){
                $orderWhere = [
                    ['send_id','=',$send_id],
                    ['stateenum','=',4],
                ];
                $orderData = (new OrderModel())->getOrderFind($orderWhere);
                if($orderData){
                    $orderStateWhere = [
                        ['worker_id_send','=',$this->workerId],
                        ['send_id','=',$send_id],
                        ['stateenum','in',[2,64]],
                        ['iscancel','=',0],
                    ];
                    $passStateOrder = (new OrderModel())->getNormalOrderFiledArr($orderStateWhere,'order_id');
                    if($passStateOrder){
                        $orderProductWaterWhere = $orderProductNormalWhere = [
                            ['order_id','in',$passStateOrder]
                        ];
                        $orderProductWaterData = (new OrderProductWater())->getNormalOrderProductWater($orderProductWaterWhere,'order_product_water_id as id,product_id,product_name,sellcount');
                        $orderProductNormalData = (new OrderProductNormal())->getNormalOrderProductNormal($orderProductNormalWhere,'order_product_normal_id as id,product_id,product_name,sellcount');
                        $orderGoodsData = array_merge($orderProductWaterData,$orderProductNormalData);
                        if($orderGoodsData){
                            $warehouseSpaceProductModel = (new WarehouseSpaceProduct());
                            foreach ($orderGoodsData as $key=>$value){
                                $warehouseSpaceProductWhere = [
                                    ['a.product_id','=',$value['product_id']],
                                    ['a.company_id','=',$this->companyId],
                                    ['a.shop_id','=',$this->shopId],
                                    ['isdel','=','0']
                                ];
                                $orderGoodsData[$key] = $warehouseSpaceProductModel->getNormalWarehouseSpaceProductFind($warehouseSpaceProductWhere,'a.warehouse_id,b.warehouse_name,a.warehouse_space_id,c.warehouse_space_name');
                            }
                        }
                    }
                }else{
                    $sendProductWhere = [
                        ['send_id','=',$send_id],
                        ['is_finish','=',1]
                    ];
                    $passOutGoodsData = (new SendProduct())->getNormalSendProduct($sendProductWhere);
                    if($passOutGoodsData){
                        foreach ($passOutGoodsData as $key=>$value){
                            if (!isset($item[$v['product_id']])) {
                                $item[$v['product_id']] = $v;
                            }else{
                                $item[$v['product_id']]['tcount'] += $v['tcount'];
                            }
                        }
                        foreach ($item as $key => $value) {
                            $itemAs[] = array(
                                'send_id'           => $value['send_id'],
                                'product_id'        => $value['product_id'],
                                'product_name'      => $value['product_name'],
                                'tcount'            => $value['tcount'],
                                'warehouse_id'      => $value['warehouse_id'],
                                'warehouse_name'    => $value['warehouse_name'],
                                'warehouse_space_id'=> $value['warehouse_space_id'],
                                'warehouse_space_name' => $value['warehouse_space_name'],
                                'adddate'           => date("Y-m-d H:i:s",time()),
                                'is_finish'         => 1,
                            );
                        }
                        $deleteAllSendProductWhere = [
                            ['send_id','=',$send_id],
                            ['is_finish','=',1],
                        ];
                        (new SendProduct())->deleteAllSendProduct($deleteAllSendProductWhere);
                        (new SendProduct())->addAllSendProduct($itemAs);
                        foreach ($goodsData as $k => $v) {
                            $sendProductWhere = [
                                ['send_id','=',$send_id],
                                ['is_finish','=',1],
                                ['product_id','=',$v['product_id']]
                            ];
                            $SendProduct = (new SendProduct())->getNormalSendProductFind($sendProductWhere,'tcount');
                            if($SendProduct){
                                $goodsData[$k]['count'] = $v['count']-$SendProduct['tcount'];
                                if($goodsData[$k]['count'] == 0){
                                    unset($goodsData[$k]);
                                }
                            }
                        }
                        $goodsData = array_values($goodsData);
                    }
                }
                $deleteAllSendProductWhere = [
                    ['send_id','=',$send_id],
                    ['is_finish','=',2],
                ];
                (new SendProduct())->deleteAllSendProduct($deleteAllSendProductWhere);
            }
        }
        if($goodsData){
            // 初始化一个空数组来存储要插入的数据
            $dataToInsert = [];
            // 循环遍历数据源，构建每一行要插入的数据
            foreach ($goodsData as $item) {
                $passProShop = (new Product())->getProductFind([['product_id','=',$item['product_id']]],'shop_id,product_name,tcount');

                if($passProShop['shop_id'] != $this->shopId){
                    return show(config('status.error'),"商品名称为".$passProShop['product_name']."的商品，不属于本店!请核实后在出厂");
                }
                if($passProShop['tcount'] < $item['tcount']){
                    return show(config('status.error'),"商品名称为".$passProShop['product_name']."的商品，库存不足!请核实后在出厂");
                }
                // 注意：确保字段名和数据类型与数据库表一致
                $row = [
                    'send_id' => $send_id, // 替换为实际的字段名和对应的值
                    'product_id' => $item['product_id'],
                    'product_name' => $item['product_name'],
                    'tcount' => $item['tcount'],
                    'warehouse_id' => $item['warehouse_id'],
                    'warehouse_name' => $item['warehouse_name'],
                    'warehouse_space_id' => $item['warehouse_space_id'],
                    'warehouse_space_name' => $item['warehouse_space_name'],
                    'adddate' => date("Y-m-d H:i:s",time()),
                    'is_finish' => 2,
                ];
                // 将构建好的数据行添加到数组中
                $dataToInsert[] = $row;
            }
            (new SendProduct())->addAllSendProduct($dataToInsert);
            $workerSaveData['sendstateenum'] = 1;
            (new Worker())->updateByWorkerId($this->workerId,$workerSaveData);
        }
        return true;
    }
}
